<template>
  <el-card>
    <template #header>管理员信息</template>
    <div>
      <p>
        <strong>管理员ID：</strong><span>{{ users.id }}</span>
      </p>
      <p>
        <strong>账号：</strong><span>{{ users.account }}</span>
      </p>
      <p>
        <strong>用户组：</strong><span>{{ users.userGroup }}</span>
      </p>
      <p>
        <strong>创建时间：</strong><span>{{ users.ctime | dateFormat }}</span>
      </p>
      <div>
        <strong>管理员头像：</strong>
        <!-- 上传头像的组件 -->
        <el-upload
          class="avatar-uploader"
          action="http://39.106.222.189:5000/users/avatar_upload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <p>
        <el-button type="primary" size="mini" @click="checkEdit"
          >确认修改</el-button
        >
      </p>
    </div>
  </el-card>
</template>

<script>
import local from '@/utils/local.js'
import { editAvatar } from '@/api/users.js'

export default {
  data() {
    return {
      imageUrl: '',
      users: {},
      // 上传成功之后的地址
      imgUrl: ''
    }
  },
  created() {
    this.users = JSON.parse(local.get('users'))

    console.log(this.users)
  },
  methods: {
    handleAvatarSuccess(res, file) {
      // 能够实现本地的预览
      this.imageUrl = URL.createObjectURL(file.raw)

      //  res指的是响应结果
      // console.log(res.imgUrl)
      this.imgUrl = res.imgUrl
    },
    beforeAvatarUpload(file) {
      // 规定死了只能是 jpeg 格式，需要一个布尔值的结果
      // const isJPG = file.type === 'image/jpeg'
      // 数组有一个是否包含的方法   includes
      const arr = [
        'image/jpeg',
        'image/png',
        'image/jpg',
        'image/webp',
        'image/gif'
      ]
      const isJPG = arr.includes(file.type)
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    async checkEdit() {
      // 没有修改则不会发请求
      if (!this.imgUrl) return ''
      const { code } = await editAvatar({
        imgUrl: this.imgUrl
      })
      if (code === 0) {
        location.reload()
      }
    }
  }
}
</script>

<style lang="less" scoped>
p {
  margin: 20px 0;
}

// 要么写到全局去，不然私有化的样式不能作用到最终编译的标签上
// 要么使用穿刺写法，这样可以使部分样式作用到编译的标签上

/deep/.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-top: 20px;
  margin-left: 20px;
}
/deep/.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  line-height: 128px;
  text-align: center;
}
.avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>
